package lyx.game.view
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	
	import lyx.game.element.GameElement;
	import lyx.game.locator.ElementLocator;
	import lyx.utils.log.Logger;

	/**
	 * 游戏可视化视图类，此类为视图的根本，负责所有视图层的渲染处理。
	 * 可以继承此类，然后在子类中添加其他视图层。
	 */	
	public class WorldView extends Sprite
	{
		private var _game_view:Bitmap = new Bitmap();
		private var _game_view_data_cache:BitmapData;
		
		public function WorldView()
		{
			initGameView();
			addEventListener(Event.ADDED_TO_STAGE,viewReady);
		}
		
		/** 
		 * 初始化视图
		 */		
		protected function initGameView(x:Number=0,y:Number=0,width:Number=640,height:Number=480):void
		{
			_game_view_data_cache = new BitmapData(width,height,false,0x555555);
			_game_view.bitmapData = new BitmapData(width,height,false,0x555555);
			_game_view.x = x;
			_game_view.y = y;
			_game_view.width = width;
			_game_view.height = height;
			addChild(_game_view);
		}
		
		private function viewReady(event:Event):void
		{
			Logger.getInstance().debug("Start View Render Engine");
			removeEventListener(Event.ADDED_TO_STAGE,viewReady);
			//when view is ready,start the view render engine
			stage.addEventListener(Event.ENTER_FRAME,viewRenderHandler);
		}
		
		/**
		 * 视图渲染处理，渲染的频率又Main中的stage.frameRate所决定。
		 * <p/>你可在子类中重构该函数实现自己的视图渲染。
		 * @param event
		 * @see Main#Main 详细参见Main类
		 */		
		protected function viewRenderHandler(event:Event):void
		{
			_game_view_data_cache.fillRect(_game_view_data_cache.rect,0x555555);
			for each(var view_element:GameElement in ElementLocator.GAME_ELEMENTS)
			{
				view_element.render(_game_view_data_cache);
			}
			_game_view.bitmapData.copyPixels(_game_view_data_cache,_game_view_data_cache.rect,new Point());
		}
		
	}
}